const router = require('koa-router')()
const { exec } = require('../db')
const { SuccessModel, FailModel } = require('../resModel')

/**
  7. 博客列表接口： get      /api/blogs
  8. 博客详情接口： get      /api/blogs/detail/:id
  9. 博客修改接口： put      /api/blogs/:id
  10. 博客增加接口： post     /api/blogs
  11. 博客删除接口： delete   /api/blogs/:id
 */

 // 博客列表查询功能
router.get('/api/blogs', async(ctx, next) => {
  const { page, size } = ctx.query;
  // 后台 验证
  const total = await exec(`select count(id) as total from blogs`)
  if (page && size) {
    const data = await exec(`select * from blogs order by id asc limit ? offset ?`,
    [Number(size), page * size]);
    // 查询当前表的总条数
    if (data.length) {
      ctx.body = new SuccessModel({data, total: total[0].total}, 'success')
    } else {
      ctx.body = new FailModel(data, 'success')
    }
  } else {
    const data = await exec(`select * from blogs order by id asc limit 10 offset 0`);
    ctx.body = new SuccessModel({data, total: total[0].total}, 'success')
  }
})

// select blogs.userid, nickname, title, content from blogs left join users on blogs.userid=users.id;
// /api/blogs/detail/:id 文章id
// 文章详情表
router.get('/api/blogs/detail/:id', async (ctx, next) => {
  // 1. 参数
  const { id } = ctx.params;
  // 2. 根据参数查询数据库
  const data = await exec(`
  select blogs.id, title, content, username from blogs left join users on blogs.author=users.id where blogs.id=?`, [id]);
  // 3. 根据数据库查询返回结果，返回给前端
  if (data.length) {
    ctx.body = new SuccessModel(data, 'success')
  } else {
    ctx.body = new FailModel('fail')
  }
})

// 博客修改接口 put      /api/blogs/:id
router.put('/api/blogs/:id', async(ctx, next) => {
  const { id } = ctx.params;
  const { title, content,  } = ctx.request.body;
  const updateData = await exec(`
   update blogs set title=?, content=? where id=?`,
   [title, content, id])
  if (updateData.affectedRows) {
    ctx.body = new SuccessModel('修改成功')
  } else {
    ctx.body = new FailModel('修改失败')
  }
})

// 当前添加数据的时候，我不知道？  涉及三个接口
/**
 * / login ---> code  临时身份id
 * / getUserInfo ---> 用户信息接口  ： openid
 * / 后台调用一个 获取 用户信息接口：
 */

//           : /api/login
// 用户信息接口：/api/userinfo
// 博客增加接口 post     /api/blogs
router.post('/api/blogs', async(ctx, next) => {
  const { title, content, author } = ctx.request.body;
  const insertData = await exec(`
  insert into blogs (title, content, author) values (?,?,?)`,
  [title, content, author]);
  if (insertData.affectedRows) {
    ctx.body = new SuccessModel({insertid: insertData.insertId}, '添加成功')
  } else {
    ctx.body = new FailModel('添加失败')
  }
})

// 博客删除接口： delete   /api/blogs/:id
router.delete('/api/blogs/:id', async(ctx, next) => {
  const { id } = ctx.params;
  const deleteBlogs = await exec(`delete from blogs where id=?`,
  [id])
  if (deleteBlogs.affectedRows) {
    ctx.body = new SuccessModel('删除成功')
  } else {
    ctx.body = new FailModel('删除失败')
  }
})

module.exports = router;